/**
 * wait() 练习
 * Created by Sean on 2017/5/9.
 */
class Thread8 implements Runnable {

    private String name;
    private Object prev;
    private Object self;

    private Thread8(String name, Object prev, Object self) {
        this.name = name;
        this.prev = prev;
        this.self = self;
    }

    @Override
    public void run() {
        int count = 10;
        while (count > 0) {
            synchronized (prev) {   //上一个对象锁，先申请上一个对象的锁，如果上个线程释放对象锁，则获取该对象锁
                synchronized (self) {   // 当前对象锁
                    System.out.print(name + ((count == 1 && name.equals("C")) ? "" : "->"));
                    count--;
                    self.notify(); // 唤醒下一个等待线程
                }
                try {
                    prev.wait();// 释放当前线程
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Object a = new Object();
        Object b = new Object();
        Object c = new Object();
        Thread8 threadA = new Thread8("A", c, a);//c是上个对象,a是当前对象
        Thread8 threadB = new Thread8("B", a, b);//a是上个对象,b是当前对象
        Thread8 threadC = new Thread8("C", b, c);//b是上个对象,c是当前对象
        new Thread(threadA).start();
        Thread.sleep(100);  //确保按顺序A、B、C执行
        new Thread(threadB).start();
        Thread.sleep(100);  //确保按顺序A、B、C执行
        new Thread(threadC).start();
        Thread.sleep(100);  //确保按顺序A、B、C执行
    }

}

public class Main8 {

}